package com.cskaoyan.market.controller.admin;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@RestController
@RequestMapping("wx/storage/fetch")
public class StorageFetchController {
    @Autowired
    ServletContext context;

    @GetMapping("/*")
    protected void uploadFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uploadBasePath= (String) context.getAttribute("upload");
        String key = req.getRequestURI().replace(req.getContextPath() + "/wx/storage/fetch/", "");
        File file = new File(uploadBasePath + key);
        if (file.exists()&&file.isFile()){
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();
            byte[] bytes = new byte[1024];
            int len =0;
            while((len = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
        }
    }
}
